<template>
  <div class="data-query-container">
    <!-- 查询条件区域 -->
    <div class="query-header">
      <a-tag color="#55acee">
        <template #icon>
          <DatabaseOutlined />
        </template>
        当前数据库: {{ currentDatabase }}
      </a-tag>
      <a-tag color="#3b5999">
        <template #icon>
          <PartitionOutlined />
        </template>
        当前表: {{ currentTable }}
      </a-tag>
    </div>

    <!-- 查询结果区域 -->
    <div class="query-result">
      <div class="result-header">
        <span class="result-title"> 查询结果 ({{ pagination.total }} 条) </span>

        <div class="pagination-controls">
          <span>每页显示:</span>
          <a-select
            v-model:value="pagination.pageSize"
            style="width: 80px; margin: 0 10px"
            @change="handlePageSizeChange"
          >
            <a-select-option :value="50">50</a-select-option>
            <a-select-option :value="100">100</a-select-option>
            <a-select-option :value="200">200</a-select-option>
          </a-select>

          <a-pagination
            v-model:current="pagination.current"
            :total="pagination.total"
            :pageSize="pagination.pageSize"
            show-less-items
            @change="handlePageChange"
          />
        </div>
      </div>

      <!-- 数据表格 -->
      <div class="result-table">
        <a-table
          :columns="columns"
          :data-source="tableData"
          :loading="queryLoading"
          :pagination="false"
          bordered
          size="small"
          :scroll="{ x: 1500, y: 600 }"
        >
          <template #bodyCell="{ column, text }">
            <template v-if="column.dataIndex === 'ts'">
              <!--              {{ formatTimestamp(text) }}-->
              {{ text }}
            </template>
            <template v-else>
              {{ text !== null ? text : 'NULL' }}
            </template>
          </template>
        </a-table>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, h, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { useMainStore } from '../store'
import {
  BookTwoTone,
  DatabaseOutlined,
  PartitionOutlined
} from '@ant-design/icons-vue'
import dayjs from 'dayjs'
import { useRoute } from 'vue-router'

const route = useRoute()
const mainStore = useMainStore()
const { ipcRenderer } = window.electron

// const currentDatabase = computed(() => mainStore.selectedComponent.currentDatabase)
// const currentTable = computed(() => mainStore.selectedComponent.currentTable)

// 数据状态
const databaseList = ref([])
const tableList = ref([])
const tableLoading = ref(false)
const queryLoading = ref(false)
const tableData = ref([])
const columns = ref([])
const currentDatabase = ref('')
const currentTable = ref('')
// 分页配置
const pagination = ref({
  current: 1,
  pageSize: 50,
  total: 0
})

// 初始化加载数据库列表
// onMounted(async () => {
//   await loadDatabases()
// })

// 加载数据库列表
// const loadDatabases = async () => {
//   try {
//     const res = await ipcRenderer.invoke('doQuery', 'SHOW DATABASES')
//     databaseList.value = res.map((item) => item[0])
//   } catch (error) {
//     message.error('加载数据库列表失败: ' + error.message)
//   }
// }

// 数据库切换时加载表列表
const handleDatabaseChange = async (db) => {
  currentTable.value = ''
  tableList.value = []
  tableLoading.value = true

  try {
    // 查询普通表和超级表
    await ipcRenderer.invoke('doQuery', `USE ${db}`)
    const tablesRes = await ipcRenderer.invoke('doQuery', 'SHOW TABLES')
    const stablesRes = await ipcRenderer.invoke('doQuery', 'SHOW STABLES')

    tableList.value = [
      ...tablesRes.map((table) => ({
        table_name: table[0],
        table_type: 'TABLE'
      })),
      ...stablesRes.map((stable) => ({
        table_name: stable[0],
        table_type: 'SUPER_TABLE'
      }))
    ]
  } catch (error) {
    message.error('加载表列表失败: ' + error.message)
  } finally {
    tableLoading.value = false
  }
}

// 表切换时加载表结构
const handleTableChange = async (table) => {
  if (!currentDatabase.value || !table) return

  try {
    // 获取表结构作为列定义
    const describeRes = await ipcRenderer.invoke(
      'doQuery',
      `DESCRIBE ${currentDatabase.value}.${table}`
    )

    columns.value = describeRes.map((col) => ({
      title: col[0],
      dataIndex: col[0],
      key: col[0],
      width: 150,
      ellipsis: true
    }))

    // 如果是超级表，添加 _tname 列显示子表名
    const isSuperTable =
      tableList.value.find((t) => t.table_name === table)?.table_type === 'SUPER_TABLE'

    if (isSuperTable) {
      columns.value.unshift({
        title: '子表名',
        dataIndex: '_tname',
        key: '_tname',
        width: 120,
        fixed: 'left'
      })
    }
  } catch (error) {
    message.error('获取表结构失败: ' + error.message)
  }
}

// 执行查询
const handleQuery = async () => {
  if (!currentDatabase.value || !currentTable.value) {
    message.warning('请选择数据库和表')
    return
  }
  queryLoading.value = true
  tableData.value = []

  try {
    await fetchTableData()
  } catch (error) {
    message.error('查询失败: ' + error.message)
  } finally {
    queryLoading.value = false
  }
}

// 获取表数据（带分页）
const fetchTableData = async () => {
  const { current, pageSize } = pagination.value
  const offset = (current - 1) * pageSize

  // 构建查询SQL
  let query = `SELECT *
               FROM ${currentDatabase.value}.${currentTable.value} `
  // 如果是超级表，添加 _tname 字段
  const isSuperTable =
    tableList.value.find((t) => t.table_name === currentTable.value)?.table_type === 'SUPER_TABLE'

  if (isSuperTable) {
    query = `SELECT _tname, *
             FROM ${currentDatabase.value}.${currentTable.value} `
  }

  // 添加分页
  query += `LIMIT ${pageSize} OFFSET ${offset}`

  // 执行查询
  const dataRes = await ipcRenderer.invoke('doQuery', query)

  // 获取总数
  const countRes = await ipcRenderer.invoke(
    'doQuery',
    `SELECT COUNT(*)
     FROM ${currentDatabase.value}.${currentTable.value}`
  )
  // 处理结果
  if (dataRes && dataRes.length > 0) {
    //查询列
    const queryCloumnsSql = 'DESCRIBE ' + currentTable.value
    const queryCloumnDataRes = await ipcRenderer.invoke('doQuery', queryCloumnsSql)
    console.log(queryCloumnDataRes, 'queryCloumnDataRes')
    if (queryCloumnDataRes && queryCloumnDataRes.length > 0) {
      columns.value = queryCloumnDataRes
        .map((col) => {
          // 如果是子表字段（非 TAG 字段），则在 title 中添加图标
          if (col[3] === 'TAG') {
            return {
              title: h('span', [
                h(BookTwoTone, {
                  style: { color: '#1890ff', marginRight: '8px' } // 设置图标的颜色和间距
                }),
                col[0]
              ]),
              dataIndex: col[0],
              key: col[0],
              width: 150,
              ellipsis: true
            }
          } else {
            // 对于 TAG 字段，只显示字段名
            return {
              title: col[0],
              dataIndex: col[0],
              key: col[0],
              width: 150,
              ellipsis: true
            }
          }
        })
        .reverse()
    }
    tableData.value = dataRes.map((row) => {
      const obj = {}
      columns.value.forEach((col, index) => {
        obj[col.key] = row[index]
      })
      return obj
    })
  }

  // 更新分页信息
  if (countRes && countRes.length > 0) {
    console.log(countRes[0][0], 'countRes')
    pagination.value.total = Number(countRes[0][0].toString())
  }
}

// 分页变化处理
const handlePageChange = (page, pageSize) => {
  pagination.value.current = page
  fetchTableData()
}

// 每页条数变化处理
const handlePageSizeChange = (size) => {
  pagination.value.pageSize = size
  pagination.value.current = 1
  fetchTableData()
}

// 重置查询
const handleReset = () => {
  currentDatabase.value = ''
  currentTable.value = ''
  tableData.value = []
  columns.value = []
  pagination.value = {
    current: 1,
    pageSize: 50,
    total: 0
  }
}

// 格式化时间戳

const formatTimestamp = (timestamp) => {
  if (!timestamp) return '/'
  return dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss')
}

onMounted(() => {
  if (route.query.currentDatabase && route.query.currentTable) {
    currentDatabase.value = route.query.currentDatabase
    currentTable.value = route.query.currentTable
    handleQuery()
  }
})

watch(
  () => route.query,
  (newQuery, oldQuery) => {
    if (route.query.currentDatabase && route.query.currentTable) {
      currentDatabase.value = newQuery.currentDatabase
      currentTable.value = newQuery.currentTable
      handleQuery()
    }
  },
  { deep: true }
)
// watch(
//   () => [currentDatabase.value, currentTable.value],
//   () => {
//     if (currentDatabase.value && currentTable.value) {
//       handleQuery()
//     }
//   },
//   { immediate: false }
// )
</script>

<style scoped>
.data-query-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 16px;
  background-color: #fff;
}

.query-header {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
}

.query-result {
  flex: 1;
  display: flex;
  flex-direction: column;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  overflow: hidden;
}

.result-header {
  padding: 8px 16px;
  background-color: #fafafa;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.result-title {
  font-weight: 500;
}

.pagination-controls {
  display: flex;
  align-items: center;
}

.result-table {
  flex: 1;
  overflow: auto;
}

:deep(.ant-table) {
  height: 100%;
}

:deep(.ant-table-container) {
  height: 100%;
  display: flex;
  flex-direction: column;
}

:deep(.ant-table-body) {
  flex: 1;
  overflow: auto !important;
}
</style>
